package com.zhaodui.pos.controller;
import com.zhaodui.loan.entity.FxjLoanMaEntity;
import com.zhaodui.order.entity.FxjOrderAttaEntity;
import com.zhaodui.order.entity.FxjOrderMainEntity;
import com.zhaodui.pos.entity.PosDetailEntity;
import com.zhaodui.pos.entity.PosXjtaskEntity;
import com.zhaodui.pos.service.PosXjtaskServiceI;
import com.zhaodui.pos.page.PosXjtaskPage;
import com.zhaodui.pos.entity.PosXjfjEntity;

import java.util.*;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhaodui.restapi.entity.FxjoutputEntity;
import com.zhaodui.util.MapHelper;
import com.zhaodui.util.fxjUtil;
import net.sf.ehcache.util.CacheTransactionHelper;
import net.sf.json.JSONObject;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.system.pojo.base.TSNotice;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.common.TreeChildCount;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;

import java.io.OutputStream;

import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.IOException;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.jwt.util.GsonUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**   
 * @Title: Controller
 * @Description: 巡检任务
 * @author onlineGenerator
 * @date 2019-04-06 07:05:23
 * @version V1.0   
 *
 */
@Api(value="PosXjtask",description="巡检任务",tags="posXjtaskController")
@Controller
@RequestMapping("/posXjtaskController")
public class PosXjtaskController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(PosXjtaskController.class);

	@Autowired
	private PosXjtaskServiceI posXjtaskService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;

	/**
	 * 巡检任务列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/zhaodui/pos/posXjtaskList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(PosXjtaskEntity posXjtask,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(PosXjtaskEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, posXjtask,request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.posXjtaskService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除巡检任务
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(PosXjtaskEntity posXjtask, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		posXjtask = systemService.getEntity(PosXjtaskEntity.class, posXjtask.getId());
		String message = "巡检任务删除成功";
		try{
			posXjtaskService.delMain(posXjtask);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "巡检任务删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 批量删除巡检任务
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		String message = "巡检任务删除成功";
		try{
			for(String id:ids.split(",")){
				PosXjtaskEntity posXjtask = systemService.getEntity(PosXjtaskEntity.class,
				id
				);
				posXjtaskService.delMain(posXjtask);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "巡检任务删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加巡检任务
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(HttpServletRequest request,PosXjtaskPage posXjtaskPage) {
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		try {
			try{
				PosDetailEntity task = systemService.findUniqueByProperty(PosDetailEntity.class, "posNo",posXjtaskPage.getPosNo());
				MyBeanUtils.copyBeanNotNull2Bean(task,posXjtaskPage);
			}catch (Exception e){

			}
			posXjtaskService.addMain(posXjtaskPage);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "巡检任务添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	/**
	 * 更新巡检任务
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(HttpServletRequest request,PosXjtaskPage posXjtaskPage) {
		AjaxJson j = new AjaxJson();
		String message = "更新成功";
		try{
			posXjtaskService.updateMain(posXjtaskPage);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "更新巡检任务失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 巡检任务新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		return new ModelAndView("com/zhaodui/pos/posXjtask-add");
	}
	
	/**
	 * 巡检任务编辑页面跳转
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(HttpServletRequest req) {
		String id = req.getParameter("id");
		PosXjtaskPage posXjtaskPage = new PosXjtaskPage();
		if (StringUtil.isNotEmpty(id)) {
			PosXjtaskEntity posXjtask = posXjtaskService.getEntity(PosXjtaskEntity.class,id);
			try {
				MyBeanUtils.copyBeanNotNull2Bean(posXjtask,posXjtaskPage);
			} catch (Exception e) {
				e.printStackTrace();
			}
			//===================================================================================
			//获取参数
			Object id0 = posXjtask.getId();
			//===================================================================================
		    //查询-附件
		    String hql0 = "from PosXjfjEntity where 1 = 1 AND posXjid = ? ";
		    List<PosXjfjEntity> posXjfjEntityList = systemService.findHql(hql0,id0);
		    if(posXjfjEntityList==null || posXjfjEntityList.size()<=0){
		    	posXjfjEntityList = new ArrayList<PosXjfjEntity>();
		    	posXjfjEntityList.add(new PosXjfjEntity());
		    }
		    posXjtaskPage.setPosXjfjList(posXjfjEntityList);
		}
		req.setAttribute("posXjtaskPage", posXjtaskPage);
		return new ModelAndView("com/zhaodui/pos/posXjtask-update");
	}
	
    /**
    * 导出excel
    *
    * @param request
    * @param response
    */
    @RequestMapping(params = "exportXls")
    public String exportXls(PosXjtaskEntity posXjtask,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,ModelMap map) {
    	CriteriaQuery cq = new CriteriaQuery(PosXjtaskEntity.class, dataGrid);
    	//查询条件组装器
    	org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, posXjtask);
    	try{
    	//自定义追加查询条件
    	}catch (Exception e) {
    		throw new BusinessException(e.getMessage());
    	}
    	cq.add();
    	List<PosXjtaskEntity> list=this.posXjtaskService.getListByCriteriaQuery(cq, false);
    	List<PosXjtaskPage> pageList=new ArrayList<PosXjtaskPage>();
        if(list!=null&&list.size()>0){
        	for(PosXjtaskEntity entity:list){
        		try{
        			PosXjtaskPage page=new PosXjtaskPage();
        			MyBeanUtils.copyBeanNotNull2Bean(entity,page);
            		Object id0 = entity.getId();
					String hql0 = "from PosXjfjEntity where 1 = 1 AND posXjid = ? ";
					List<PosXjfjEntity> posXjfjEntityList = systemService.findHql(hql0,id0);
					page.setPosXjfjList(posXjfjEntityList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
        map.put(NormalExcelConstants.FILE_NAME,"巡检任务");
        map.put(NormalExcelConstants.CLASS,PosXjtaskPage.class);
        map.put(NormalExcelConstants.PARAMS,new ExportParams("巡检任务列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        map.put(NormalExcelConstants.DATA_LIST,pageList);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}

    /**
	 * 通过excel导入数据
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(2);
			params.setNeedSave(true);
			try {
				List<PosXjtaskEntity> list =  ExcelImportUtil.importExcel(file.getInputStream(), PosXjtaskEntity.class, params);
				for (PosXjtaskEntity page : list) {
					PosDetailEntity	task = systemService.findUniqueByProperty(PosDetailEntity.class, "posNo",page.getPosNo());
                    MyBeanUtils.copyBeanNotNull2Bean(task,page);
					page.setBpmStatus("1");
					systemService.save(page);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			}
			return j;
	}
	/**
	* 导出excel 使模板
	*/
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(ModelMap map) {
		map.put(NormalExcelConstants.FILE_NAME,"巡检任务");
		map.put(NormalExcelConstants.CLASS,PosXjtaskEntity.class);
		map.put(NormalExcelConstants.PARAMS,new ExportParams("巡检任务列表", "导出人:"+ ResourceUtil.getSessionUser().getRealName(),
		"导出信息"));
		map.put(NormalExcelConstants.DATA_LIST,new ArrayList());
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	* 导入功能跳转
	*
	* @return
	*/
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name", "posXjtaskController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}


	@RequestMapping(value="/list/{username}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="巡检任务列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<PosXjtaskPage>> list(@PathVariable("username") String username, @RequestParam int pageNumber, @RequestParam int pageSize, HttpServletRequest request) {
		if(pageSize>Globals.MAX_PAGESIZE){
			return Result.error("每页请求不能超过" + Globals.MAX_PAGESIZE + "条");
		}
		CriteriaQuery query = new CriteriaQuery(PosXjtaskEntity.class);
		TSUser task = fxjUtil.getsysorgcode(username);
		String orgcode = "";
		if (task != null) {
			query.eq("posJhxjUser", task.getUserName());
		}
		if(StringUtil.isNotEmpty(request.getParameter("bpmStatus"))){
			query.eq("bpmStatus",request.getParameter("bpmStatus"));
		}
		if(StringUtil.isNotEmpty(request.getParameter("posXjType"))){
			query.eq("posXjType",request.getParameter("posXjType"));
		}
		if(StringUtil.isNotEmpty(request.getParameter("posNo"))){
			query.eq("posNo",request.getParameter("posNo"));
		}
		query.add();
		List<PosXjtaskEntity> listsize = this.posXjtaskService.getListByCriteriaQuery(query,false);
		query.setCurPage(pageNumber<=0?1:pageNumber);
		query.setPageSize(pageSize<1?1:pageSize);
		query.add();

		List<PosXjtaskEntity> list = this.posXjtaskService.getListByCriteriaQuery(query,true);

    	List<PosXjtaskPage> pageList=new ArrayList<PosXjtaskPage>();
        if(list!=null&&list.size()>0){
        	for(PosXjtaskEntity entity:list){
        		try{
        			PosXjtaskPage page=new PosXjtaskPage();
        		   MyBeanUtils.copyBeanNotNull2Bean(entity,page);
					Object id0 = entity.getId();
				    String hql0 = "from PosXjfjEntity where 1 = 1 AND posXjid = ? ";
	    			List<PosXjfjEntity> posXjfjOldList = this.posXjtaskService.findHql(hql0,id0);
				    page.setPosXjfjList(posXjfjOldList);
            		pageList.add(page);
            	}catch(Exception e){
            		logger.info(e.getMessage());
            	}
            }
        }
		return Result.success(pageList,(long)listsize.size());
	}

	@RequestMapping(value="/listbyposno/{posNo}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="巡检任务列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<PosXjtaskPage>> listbyposno(@PathVariable("posNo") String posNo, @RequestParam int pageNumber, @RequestParam int pageSize, HttpServletRequest request) {
		if(pageSize>Globals.MAX_PAGESIZE){
			return Result.error("每页请求不能超过" + Globals.MAX_PAGESIZE + "条");
		}
		CriteriaQuery query = new CriteriaQuery(PosXjtaskEntity.class);

		if(StringUtil.isNotEmpty(request.getParameter("bpmStatus"))){
			query.eq("bpmStatus",request.getParameter("bpmStatus"));
		}
		if(StringUtil.isNotEmpty(request.getParameter("posXjType"))){
			query.eq("posXjType",request.getParameter("posXjType"));
		}
 			query.eq("posNo",posNo);

		query.add();
		List<PosXjtaskEntity> listsize = this.posXjtaskService.getListByCriteriaQuery(query,false);
		query.setCurPage(pageNumber<=0?1:pageNumber);
		query.setPageSize(pageSize<1?1:pageSize);
		query.add();

		List<PosXjtaskEntity> list = this.posXjtaskService.getListByCriteriaQuery(query,true);

		List<PosXjtaskPage> pageList=new ArrayList<PosXjtaskPage>();
		if(list!=null&&list.size()>0){
			for(PosXjtaskEntity entity:list){
				try{
					PosXjtaskPage page=new PosXjtaskPage();
					MyBeanUtils.copyBeanNotNull2Bean(entity,page);
					Object id0 = entity.getId();
					String hql0 = "from PosXjfjEntity where 1 = 1 AND posXjid = ? ";
					List<PosXjfjEntity> posXjfjOldList = this.posXjtaskService.findHql(hql0,id0);
					page.setPosXjfjList(posXjfjOldList);
					pageList.add(page);
				}catch(Exception e){
					logger.info(e.getMessage());
				}
			}
		}
		return Result.success(pageList,(long)listsize.size());
	}

	@RequestMapping(value="/fjlist/{username}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="附近巡检任务列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<PosXjtaskPage>> fujinlist(@PathVariable("username") String username, @RequestParam int pageNumber, @RequestParam int pageSize,@RequestParam(value="jingdu", required=true) String jingdu,@RequestParam(value="weidu", required=true) String weidu, HttpServletRequest request) {
		if(pageSize>Globals.MAX_PAGESIZE){
			return Result.error("每页请求不能超过" + Globals.MAX_PAGESIZE + "条");
		}
		CriteriaQuery query = new CriteriaQuery(PosXjtaskEntity.class);
		TSUser task = fxjUtil.getsysorgcode(username);
		String orgcode = "";
		if (task != null) {
			query.eq("posJhxjUser", task.getUserName());
		}
		if(StringUtil.isNotEmpty(request.getParameter("bpmStatus"))){
			query.eq("bpmStatus",request.getParameter("bpmStatus"));
		}
		if(StringUtil.isNotEmpty(request.getParameter("posXjType"))){
			query.eq("posXjType",request.getParameter("posXjType"));
		}
		if(StringUtil.isNotEmpty(request.getParameter("posNo"))){
			query.eq("posNo",request.getParameter("posNo"));
		}
		if(StringUtil.isNotEmpty(request.getParameter("posName"))){
			query.eq("posName",request.getParameter("posName"));
		}
		query.add();
		List<PosXjtaskEntity> listsize = this.posXjtaskService.getListByCriteriaQuery(query,false);
		query.setCurPage(pageNumber<=0?1:pageNumber);
		query.setPageSize(pageSize<1?1:pageSize);
		query.add();

		List<PosXjtaskEntity> list = this.posXjtaskService.getListByCriteriaQuery(query,true);

		List<PosXjtaskPage> pageList=new ArrayList<PosXjtaskPage>();
		if(list!=null&&list.size()>0){
			for(PosXjtaskEntity entity:list){
				try{

					//计算距离
					try{
						double firstRadLat = Double.parseDouble(weidu);
						double firstRadLng = Double.parseDouble(jingdu);
						double secondRadLat =Double.parseDouble(entity.getPosWeidu());
						double secondRadLng = Double.parseDouble(entity.getPosJingdu());
						Double juli = MapHelper.getDistance(firstRadLat,firstRadLng,secondRadLat,secondRadLng);
						entity.setPosJuli(Double.toString(juli));
					}catch (Exception e){

					}

					//计算距离

					PosXjtaskPage page=new PosXjtaskPage();
					MyBeanUtils.copyBeanNotNull2Bean(entity,page);
					Object id0 = entity.getId();
					String hql0 = "from PosXjfjEntity where 1 = 1 AND posXjid = ? ";
					List<PosXjfjEntity> posXjfjOldList = this.posXjtaskService.findHql(hql0,id0);
					page.setPosXjfjList(posXjfjOldList);
					pageList.add(page);

				}catch(Exception e){
					logger.info(e.getMessage());
				}
			}
			Collections.sort(pageList, new Comparator<PosXjtaskPage>() {

				public int compare(PosXjtaskPage h1, PosXjtaskPage h2) {
					return h1.getPosJuli().compareTo(h2.getPosJuli());
				}
			});
		}
		return Result.success(pageList,(long)listsize.size());
	}

	@RequestMapping(value="/getNotice/{username}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="附近巡检任务列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<TSNotice>> getNotice(@PathVariable("username") String username, HttpServletRequest request) {

		List<TSNotice> list = new ArrayList<>();
		CriteriaQuery query = new CriteriaQuery(PosXjtaskEntity.class);
		TSUser task = fxjUtil.getsysorgcode(username);
		List<Map<String, Object>> resultList2 = null;
		String orgcode = "";
		Integer isRead = null;
		if (task != null) {
			try {

				String sql = "SELECT notice.*,noticeRead.is_read as is_read FROM t_s_notice notice "
						+ "LEFT JOIN t_s_notice_read_user noticeRead ON  notice.id = noticeRead.notice_id "
						+ "WHERE noticeRead.del_flag = 0 and noticeRead.user_id = ? ";
				sql += " and noticeRead.is_read = ? ";
				sql += " ORDER BY noticeRead.create_time DESC ";
				if (isRead == null || !(isRead == 1 || isRead == 0)) {
					isRead = 0;
				}
				List<Map<String, Object>> noticeList = systemService.findForJdbcParam(sql, 1, 10, task.getId(), isRead.intValue());

				//将List转换成JSON存储
				net.sf.json.JSONArray result = new net.sf.json.JSONArray();
				if (noticeList != null && noticeList.size() > 0) {
					for (int i = 0; i < noticeList.size(); i++) {
						TSNotice tsNotice = new TSNotice();
						tsNotice.setId(noticeList.get(i).get("id").toString());
						tsNotice.setNoticeTitle(noticeList.get(i).get("notice_title").toString());
						tsNotice.setNoticeContent(noticeList.get(i).get("notice_content").toString());
						list.add(tsNotice);
					}
				}
				//获取通知公告总数
				String sql2 = "SELECT count(notice.id) as count FROM t_s_notice notice "
						+ "LEFT JOIN t_s_notice_read_user noticeRead ON  notice.id = noticeRead.notice_id "
						+ "WHERE noticeRead.del_flag = 0 and noticeRead.user_id = ? "
						+ "and noticeRead.is_read = 0";
				resultList2 = systemService.findForJdbc(sql2, task.getId());


			}
			catch (Exception e){

			}
		}
		return Result.success(list, Long.parseLong(resultList2.get(0).get("count").toString()));

	}







	@RequestMapping(value = "/gettj/{username}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据username获取统计信息",notes="根据username获取统计信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> getbi(@ApiParam(required=true,name="username",value="username")@PathVariable("username") String username) {
		List<FxjoutputEntity> res = new ArrayList<>();
		TSUser task = fxjUtil.getsysorgcode(username);
		String orgcode = "";
		if (task != null) {
			String tsql = "select bpm_status,count(*) as counts from pos_xjtask where pos_jhxj_user ='"+username+"' group by bpm_status ";
			List<Map<String, Object>> resultz  = systemService.findForJdbc(tsql);
			Map<String, Object> map;
			if (resultz.size() > 0) {
				for (Map<String, Object> object : resultz) {
					for (int i = 0; i < resultz.size(); i++) {
						FxjoutputEntity fxjoutputEntity = new FxjoutputEntity();


						try {
							fxjoutputEntity.setFxjx1(resultz.get(i).get("bpm_status").toString());

							fxjoutputEntity.setFxjx2(resultz.get(i).get("counts").toString());
						}catch (Exception e){

						}
						if("1".equals(fxjoutputEntity.getFxjx1())){
							fxjoutputEntity.setFxjx1("未完成");
						}
						res.add(fxjoutputEntity);
					}
				}
			}
		}

		return Result.success(res);
	}


	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ID获取巡检任务信息",notes="根据ID获取巡检任务信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> get(@ApiParam(required=true,name="id",value="ID")@PathVariable("id") String id) {

		PosXjtaskEntity task = posXjtaskService.get(PosXjtaskEntity.class, id);
		if (task == null) {
			return Result.error("根据ID获取巡检任务信息为空");
		}
		PosXjtaskPage page = new PosXjtaskPage();
		try {
			try{
				String imgserver = ResourceUtil.getConfigByName("img.server");
				String imgpath = ResourceUtil.getConfigByName("showAndDownUrl");

				task.setShPic1(imgserver+imgpath+task.getShPic1());
				task.setShPic2(imgserver+imgpath+task.getShPic2());
				task.setShYyzz(imgserver+imgpath+task.getShYyzz());
				task.setShShxy(imgserver+imgpath+task.getShShxy());
				task.setShOtherpic(imgserver+imgpath+task.getShOtherpic());
			}catch (Exception e0){

			}
			MyBeanUtils.copyBeanNotNull2Bean(task, page);

				Object id0 = task.getId();
		    String hql0 = "from PosXjfjEntity where 1 = 1 AND posXjid = ? ";
			List<PosXjfjEntity> posXjfjOldList = this.posXjtaskService.findHql(hql0,id0);
		    page.setPosXjfjList(posXjfjOldList);
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.success(page);
	}
	@RequestMapping(value="/filelist/{posXjid}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="订单file信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<PosXjfjEntity>> filelist(@PathVariable("posXjid") String posXjid, @RequestParam(value="attaType", required=false) String attaType, HttpServletRequest request) {


		String hql0 = "from PosXjfjEntity where 1 = 1 AND posXjid = ? ";
		if(StringUtil.isNotEmpty(attaType)){
			hql0 = "from PosXjfjEntity where 1 = 1 AND posXjid = ? and posXjfjname = '" +attaType+"'";
		}
		List<PosXjfjEntity> posXjfjOldList = this.posXjtaskService.findHql(hql0,posXjid);
		return Result.success(posXjfjOldList);
	}
 	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="创建巡检任务")
	public ResponseMessage<?> create(@ApiParam(name="巡检任务对象")@RequestBody PosXjtaskPage posXjtaskPage, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<PosXjtaskPage>> failures = validator.validate(posXjtaskPage);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}
		try{
			try{
				PosDetailEntity task = systemService.findUniqueByProperty(PosDetailEntity.class, "posNo",posXjtaskPage.getPosNo());
				posXjtaskPage.setBpmStatus("1");
				MyBeanUtils.copyBeanNotNull2Bean(task,posXjtaskPage);
			}catch (Exception e){

			}
			posXjtaskService.addMain(posXjtaskPage);
		}catch(Exception e){
            logger.info(e.getMessage());
            return Result.error("保存巡检任务失败");
        }
		return Result.success();
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="更新巡检任务",notes="更新巡检任务")
	public ResponseMessage<?> update(@RequestBody PosXjtaskEntity posXjtaskPage) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<PosXjtaskEntity>> failures = validator.validate(posXjtaskPage);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}
		try {
			PosXjtaskEntity xj = systemService.get(PosXjtaskEntity.class,posXjtaskPage.getId());
			xj.setPosSjxjTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
			xj.setWzChayi("一致");
				//计算距离
				try{
					double firstRadLat = Double.parseDouble(posXjtaskPage.getSjWendu());
					double firstRadLng = Double.parseDouble(posXjtaskPage.getSjJingdu());
					double secondRadLat =Double.parseDouble(xj.getPosWeidu());
					double secondRadLng = Double.parseDouble(xj.getPosJingdu());
					Double juli = MapHelper.getDistance(firstRadLat,firstRadLng,secondRadLat,secondRadLng)*1000;
					 if (juli>=250){
					 	xj.setWzChayi("不一致");
					 }
				}catch (Exception e){

				}

			MyBeanUtils.copyBeanNotNull2Bean(posXjtaskPage,xj);
			systemService.updateEntitie(xj);
		} catch (Exception e) {
			logger.info(e.getMessage());
	        return Result.error("更新巡检任务失败");
		}
		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success();
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value="删除巡检任务")
	public ResponseMessage<?> delete(@ApiParam(name="id",value="ID",required=true)@PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			PosXjtaskEntity posXjtask = posXjtaskService.get(PosXjtaskEntity.class, id);
			posXjtaskService.delMain(posXjtask);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("巡检任务删除失败");
		}

		return Result.success();
	}
	
}
